import React, { useEffect, useRef, useState } from 'react'
import { getGoods, changeCardList, delCount } from '../../store/models/goods'
import type {GoodsList} from '../../store/models/goods'
import style from './Goods.module.scss'
import classNames from 'classnames'
import Card from './components/card/Card'
import { useNavigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { RootState,AppDispatch } from '../../store/index'




const Goods:React.FC = () => {
  const [curIndex,setCurIndex] = useState(0)
  const scrollRef = useRef<HTMLDivElement>(null)
  const navigate = useNavigate()
  const dispatch:AppDispatch = useDispatch()
  const goods = useSelector((state:RootState) => state.goods.goodsList)
  const cardList = useSelector((state:RootState) => state.goods.cardList)
  // 找到每一项距离顶部的距离 存滚动的子元素到父元素的距离
  const goodsItemOffsetTop = useRef<number[]>([])
  const isScroll = useRef(false)
  const timer = useRef<number | null>(null)

  // console.log(cardList)
  useEffect(() => {
    dispatch(getGoods())
  },[])

useEffect(() => {
  goodsItemOffsetTop.current = [...scrollRef.current!.children].map(item => (item as HTMLDivElement).offsetTop)
  console.log(goodsItemOffsetTop.current)
},[goods])


  const jump = (index:number) => {
    if(timer.current) clearTimeout(timer.current)
    isScroll.current = true
    scrollRef.current!.scrollTop = (scrollRef.current!.children[index] as HTMLElement).offsetTop
    setCurIndex(index)
    timer.current = setTimeout(() => {
      isScroll.current = false
    },800)
  }

  const onScroll = (e:React.UIEvent<HTMLElement, UIEvent>) => {
    if(isScroll.current) return 
    // console.log((e.target as HTMLDivElement).scrollTop)
    const scrollTop = (e.target as HTMLDivElement).scrollTop
    const index = goodsItemOffsetTop.current.findIndex((item,index) => {
      if(index === goodsItemOffsetTop.current.length - 1) {
        return scrollTop >= item
      }
      return scrollTop >= item && scrollTop < goodsItemOffsetTop.current[index + 1]
    })
    // console.log(index)
    setCurIndex(index)
  }


  const goDetail = (data:GoodsList) => {
    console.log(data)
    navigate('/detail',{state:{data}})
  }


  return (
    <div className={style.boxWrap}>
      <div className={style.box}> 
        <nav className={style.left}>
        {goods.map((item,index) =>
          <p 
          key={item.name}
          onClick={() => jump(index)}
          className={classNames({[style.active]:curIndex === index})}
          >{item.name}</p>
        )}
        </nav>
        <main className={style.right} ref={scrollRef} onScroll={onScroll}>
          {goods.map(item => 
            <ul key={item.name}>
              <h5>{item.name}</h5>
              {item.foods.map(it =>
                <li key={it.name}>
                  <div onClick={() => goDetail(it)} className={style.con}>
                    <img src={it.image} alt="" />
                    <div className={style.content}>
                      <h4>{it.name}</h4>
                      <p>{it.description}</p>
                      <div className={style.rating}>
                        <p>月售{it.sellCount}单</p>
                        <p>好评率{it.rating}%</p>
                      </div>
                    </div>
                  </div>
                  <div className={style.price}>
                    <h6>￥{it.price}</h6>
                    {cardList.find(v => v.name === it.name)?
                    <div>
                      <button className={style.delCount} onClick={() => dispatch(delCount(it))}>-</button>
                      <span>{cardList.find(v=>v.name === it.name)?.count}</span>
                      <button className={style.addCount} onClick={() => dispatch(changeCardList(it))}>+</button>
                    </div>
                    :
                    <button className={style.addCount} onClick={() => dispatch(changeCardList(it))}>+</button>
                    }
                  </div>
                </li>
              )}
            </ul>
          )}
        </main>
      </div>
      {cardList.length > 0 && <Card />}
    </div>
  )
}



export default Goods